<template>
  <div class="medical-advice-container">
    <div class="page-header">
      <h1>医嘱管理</h1>
      <div class="patient-selector">
        <span>当前患者：</span>
        <el-select 
          v-model="selectedPatientId" 
          filterable 
          placeholder="请选择患者" 
          @change="handlePatientChange"
          class="patient-select"
        >
          <el-option
            v-for="patient in patients"
            :key="patient.id"
            :label="patient.name + ' (ID: ' + patient.id + ')'"
            :value="patient.id"
          >
            <div class="patient-option">
              <div class="patient-option-info">
                <div>{{ patient.name }}</div>
                <div class="patient-option-id">ID: {{ patient.id }}</div>
              </div>
            </div>
          </el-option>
        </el-select>
      </div>
    </div>

    <div v-if="selectedPatient" class="patient-info-card">
      <el-card>
        <div class="patient-info-header">
          <div class="patient-basic-info">
            <h2>{{ selectedPatient.name }}</h2>
            <div class="patient-details">
              <span><el-icon><User /></el-icon> {{ selectedPatient.gender === 0 ? '男' : '女' }}, {{ selectedPatient.age }}岁</span>
              <span><el-icon><Phone /></el-icon> 联系方式: {{ selectedPatient.contact }}</span>
              <span><el-icon><Calendar /></el-icon> 入院日期: {{ formatDate(selectedPatient.admissionDate) }}</span>
              <el-tag :type="selectedPatient.patientStatus === 0 ? 'success' : 'danger'">
                {{ selectedPatient.patientStatus === 0 ? '正常' : '异常' }}
              </el-tag>
            </div>
          </div>
          <div class="patient-actions">
            <el-button type="primary" @click="handleCreateMedicalAdvice">
              <el-icon><Plus /></el-icon> 添加医嘱
            </el-button>
            <el-button @click="handlePrintMedicalAdvice" v-if="treatmentPlansList.length > 0">
              <el-icon><Printer /></el-icon> 打印医嘱
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <div v-if="selectedPatient" class="medical-advice-content">
      <el-card class="medical-advice-card">
        <template #header>
          <div class="card-header">
            <span>医嘱列表</span>
            <div class="header-actions">
              <el-input
                v-model="searchQuery"
                placeholder="搜索医嘱内容"
                :prefix-icon="Search"
                clearable
                @clear="handleSearch"
                @input="handleSearch"
                style="width: 250px;"
              >
              </el-input>
            </div>
          </div>
        </template>

        <div v-if="treatmentPlansList.length > 0">
          <el-table :data="filteredTreatmentPlans" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="编号" width="80" />
            <el-table-column prop="treatmentDescription" label="医嘱内容" min-width="300" show-overflow-tooltip />
            <el-table-column label="开始日期" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.startDate) }}
              </template>
            </el-table-column>
            <el-table-column label="结束日期" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.endDate) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getMedicalAdviceStatus(scope.row)">
                  {{ getMedicalAdviceStatusText(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="handleViewMedicalAdvice(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="handleEditMedicalAdvice(scope.row)">编辑</el-button>
                <el-popconfirm
                  title="确定删除该医嘱吗？"
                  @confirm="handleDeleteMedicalAdvice(scope.row)"
                >
                  <template #reference>
                    <el-button size="small" type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="empty-data">
          <el-empty description="暂无医嘱记录" />
          <el-button type="primary" @click="handleCreateMedicalAdvice">添加医嘱</el-button>
        </div>
      </el-card>
    </div>

    <!-- 医嘱编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="medicalAdviceFormRef" :model="medicalAdviceForm" :rules="medicalAdviceRules" label-width="100px">
        <el-form-item label="医嘱内容" prop="treatmentDescription">
          <el-input 
            v-model="medicalAdviceForm.treatmentDescription" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入医嘱内容"
          />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="medicalAdviceForm.startDate"
            type="datetime"
            placeholder="选择开始日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="medicalAdviceForm.endDate"
            type="datetime"
            placeholder="选择结束日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMedicalAdviceForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 医嘱详情对话框 -->
    <el-dialog
      title="医嘱详情"
      v-model="detailDialogVisible"
      width="500px"
      append-to-body
    >
      <div v-if="selectedMedicalAdvice" class="medical-advice-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="医嘱内容">{{ selectedMedicalAdvice.treatmentDescription }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ formatDate(selectedMedicalAdvice.startDate) }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ formatDate(selectedMedicalAdvice.endDate) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getMedicalAdviceStatus(selectedMedicalAdvice)">
              {{ getMedicalAdviceStatusText(selectedMedicalAdvice) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditMedicalAdvice(selectedMedicalAdvice)">编辑</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Edit, 
  Printer, 
  Calendar, 
  Phone,
  Plus,
  Search
} from '@element-plus/icons-vue'
import { listPatients, getPatients } from '@/api/patients'
import { 
  listTreatmentplans, 
  getTreatmentplans,
  addTreatmentplans, 
  updateTreatmentplans, 
  delTreatmentplans 
} from '@/api/treatmentplans'

const route = useRoute()
const router = useRouter()

// 患者数据
const patients = ref([])
const selectedPatientId = ref(null)
const selectedPatient = ref(null)
const loading = ref(false)

// 医嘱相关数据
const treatmentPlansList = ref([])
const searchQuery = ref('')

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const detailDialogVisible = ref(false)
const selectedMedicalAdvice = ref(null)

// 表单数据
const medicalAdviceForm = reactive({
  id: null,
  patientId: null,
  treatmentDescription: '',
  startDate: new Date(),
  endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 默认一周后结束
})

// 表单验证规则
const medicalAdviceRules = {
  treatmentDescription: [{ required: true, message: '请输入医嘱内容', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
}

// 表单引用
const medicalAdviceFormRef = ref(null)

// 过滤后的医嘱列表
const filteredTreatmentPlans = computed(() => {
  if (!searchQuery.value) {
    return treatmentPlansList.value
  }
  
  const query = searchQuery.value.toLowerCase()
  return treatmentPlansList.value.filter(plan => 
    plan.treatmentDescription.toLowerCase().includes(query)
  )
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化日期为后端需要的格式
const formatDateForBackend = (date) => {
  if (!date) return null
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取医嘱状态
const getMedicalAdviceStatus = (medicalAdvice) => {
  const now = new Date()
  const startDate = new Date(medicalAdvice.startDate)
  const endDate = new Date(medicalAdvice.endDate)
  
  if (now < startDate) {
    return 'info' // 未开始
  } else if (now > endDate) {
    return 'success' // 已完成
  } else {
    return 'warning' // 执行中
  }
}

// 获取医嘱状态文本
const getMedicalAdviceStatusText = (medicalAdvice) => {
  const now = new Date()
  const startDate = new Date(medicalAdvice.startDate)
  const endDate = new Date(medicalAdvice.endDate)
  
  if (now < startDate) {
    return '未开始'
  } else if (now > endDate) {
    return '已完成'
  } else {
    return '执行中'
  }
}

// 获取患者列表
const getPatientList = async () => {
  loading.value = true
  try {
    const response = await listPatients()
    patients.value = response
    
    // 如果URL中有patientId参数，则选中对应患者
    const patientId = route.query.patientId
    if (patientId) {
      selectedPatientId.value = parseInt(patientId)
      handlePatientChange(selectedPatientId.value)
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('获取患者列表失败')
  } finally {
    loading.value = false
  }
}

// 处理患者选择变化
const handlePatientChange = async (patientId) => {
  if (!patientId) return
  
  loading.value = true
  try {
    // 获取患者详情
    const patientResponse = await getPatients(patientId)
    selectedPatient.value = patientResponse
    
    // 更新URL参数
    router.push({
      query: { ...route.query, patientId }
    })
    
    // 加载医嘱列表
    await loadTreatmentPlansList(patientId)
    
  } catch (error) {
    console.error('获取患者详情失败:', error)
    ElMessage.error('获取患者详情失败')
  } finally {
    loading.value = false
  }
}

// 加载医嘱列表
const loadTreatmentPlansList = async (patientId) => {
  try {
    const response = await listTreatmentplans({ patientId })
    treatmentPlansList.value = response
  } catch (error) {
    console.error('获取医嘱列表失败:', error)
    ElMessage.error('获取医嘱列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  // 使用计算属性自动过滤
}

// 处理查看医嘱详情
const handleViewMedicalAdvice = (medicalAdvice) => {
  selectedMedicalAdvice.value = medicalAdvice
  detailDialogVisible.value = true
}

// 处理创建医嘱
const handleCreateMedicalAdvice = () => {
  if (!selectedPatient.value) {
    ElMessage.warning('请先选择患者')
    return
  }
  
  // 重置表单
  medicalAdviceForm.id = null
  medicalAdviceForm.patientId = selectedPatient.value.id
  medicalAdviceForm.treatmentDescription = ''
  medicalAdviceForm.startDate = new Date()
  medicalAdviceForm.endDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
  
  dialogTitle.value = '添加医嘱'
  dialogVisible.value = true
}

// 处理编辑医嘱
const handleEditMedicalAdvice = (medicalAdvice) => {
  // 关闭详情对话框
  detailDialogVisible.value = false
  
  // 设置表单数据
  medicalAdviceForm.id = medicalAdvice.id
  medicalAdviceForm.patientId = medicalAdvice.patientId
  medicalAdviceForm.treatmentDescription = medicalAdvice.treatmentDescription
  medicalAdviceForm.startDate = new Date(medicalAdvice.startDate)
  medicalAdviceForm.endDate = new Date(medicalAdvice.endDate)
  
  dialogTitle.value = '编辑医嘱'
  dialogVisible.value = true
}

// 处理删除医嘱
const handleDeleteMedicalAdvice = async (medicalAdvice) => {
  try {
    await delTreatmentplans(medicalAdvice.id)
    ElMessage.success('删除医嘱成功')
    
    // 重新加载医嘱列表
    await loadTreatmentPlansList(selectedPatient.value.id)
  } catch (error) {
    console.error('删除医嘱失败:', error)
    ElMessage.error('删除医嘱失败')
  }
}

// 提交医嘱表单
const submitMedicalAdviceForm = () => {
  medicalAdviceFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 格式化日期为后端需要的格式
        const formData = {
          ...medicalAdviceForm,
          startDate: formatDateForBackend(medicalAdviceForm.startDate),
          endDate: formatDateForBackend(medicalAdviceForm.endDate)
        }
        
        if (medicalAdviceForm.id) {
          // 编辑医嘱
          await updateTreatmentplans(formData)
          ElMessage.success('更新医嘱成功')
        } else {
          // 添加医嘱
          await addTreatmentplans(formData)
          ElMessage.success('添加医嘱成功')
        }
        
        dialogVisible.value = false
        
        // 重新加载医嘱列表
        await loadTreatmentPlansList(selectedPatient.value.id)
      } catch (error) {
        console.error('保存医嘱失败:', error)
        ElMessage.error('保存医嘱失败')
      }
    }
  })
}

// 处理打印医嘱
const handlePrintMedicalAdvice = () => {
  ElMessage.info('打印功能开发中...')
}

// 生命周期钩子
onMounted(() => {
  getPatientList()
})
</script>

<style scoped>
.medical-advice-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.patient-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.patient-select {
  width: 250px;
}

.patient-option {
  display: flex;
  align-items: center;
}

.patient-option-info {
  margin-left: 10px;
}

.patient-option-id {
  font-size: 12px;
  color: #909399;
}

.patient-info-card {
  margin-bottom: 20px;
}

.patient-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-basic-info {
  display: flex;
  flex-direction: column;
}

.patient-basic-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.patient-details {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.patient-actions {
  display: flex;
  gap: 10px;
}

.medical-advice-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.medical-advice-detail {
  padding: 10px;
}
</style> 
